package wap.rockvilletech.portal;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

@SuppressWarnings("serial")
public class ContentServlet extends HttpServlet {
	
	private static final Logger log = Logger.getLogger(ContentServlet.class);
	private static final String insertContentSql = "INSERT INTO content (ContentID, ContentName, CategoryID, CategoryName, OriginalFile, " +
			"Price, Status, ProviderID, ContentImage, Format, AspectRatio, SingerOrFilm, ContentSequence, OrderSequence, " +
			"InsertionTime, CategoryType, Description, MainCat, IsAuthorized, UpdatedAt, Point1, Point2, Bias, " +
			"FillColor, DownloadTimes) " +
			"VALUES (?, ?, ?, ?, ?, " +
			"?, 1, 1, ?, ?, 1, ?, 1, 2, " +
			"now(), ?, ?, ?, 1, now(), ?, ?, ?, ?, 0);";
	private static final String nextContentIdSql = "select max(contentid) as cntid from content";

	protected void processRequest(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		String csvFileName = req.getParameter("fn"); 
		if(!(csvFileName == null || csvFileName.isEmpty())) {
			try {
				int tmpIndex = 0;
				if( (tmpIndex = csvFileName.indexOf("content/")) == -1 || !csvFileName.endsWith(".csv")) {
					log.warn("**Returning** Invalid file format, csvFileName:"+csvFileName);
					return;
				}
				tmpIndex += 8;
				String contentType = csvFileName.substring((tmpIndex), csvFileName.indexOf("/", (tmpIndex)));
				File csvFile = new File(csvFileName);
				if(!csvFile.exists() || csvFile.length() <= 1) {
					log.warn("**Returning** Invalid CSV file, csvFileName:"+csvFileName);
					return;
				}				
//				BufferedInputStream bis = new BufferedInputStream(new FileInputStream(csvFile));
				BufferedReader br = new BufferedReader(new FileReader(csvFile));
				String csvStr;
				log.debug("ContentType: "+contentType+", csvFile: "+csvFileName);
				if("wallpapers".equals(contentType)) {
					int c = 0;
					while((csvStr = br.readLine()) != null) {
						log.debug("data["+(c++)+"] "+csvStr);
						String [] fileData = csvStr.split(",");
						if(fileData.length == 6)
							addWallPaper(fileData);
					}					
				}
				
			} catch(Exception e) {
				log.error("", e);
			}
		}
		else {
			log.warn("required parameter missing: csvFileName:"+csvFileName);
		}
	}
	
	private void addWallPaper(String fileData[]) {
		Connection conn = null;
		PreparedStatement ps = null;
		DBProc dbProc = DBProc.getInstance();
		try {
			conn = dbProc.getJNDIConnection();			
			ps = conn.prepareStatement(nextContentIdSql);
			ResultSet rs = ps.executeQuery();
			int nextCntId = 1001;
			if(rs.next()) {
				nextCntId = rs.getInt(1)+1;
			}
			String originalFile = fileData[0];
			String sampleImage = fileData[1];
			String point1 = fileData[2];
			String point2 = fileData[3];
			String bias = fileData[4];
			String fillColor = fileData[5];
			//home/aak/content/wallpapers/Bollywood/BadmaashCompany/wallpaper_1.jpg
			String categoryId = SystemProperty.getProperty("wallpaper_cate_id");			
			String categoryName = "WALLPAPERS";
			String price = SystemProperty.getProperty("wallpaper_price");
			int tmpIndex = originalFile.lastIndexOf(".");
			String contentName = originalFile.substring(originalFile.lastIndexOf("/")+1, tmpIndex);			
			String ext = originalFile.substring(tmpIndex+1);
			tmpIndex = originalFile.indexOf("/content/")+9;
			
			String tempString  = originalFile.substring(originalFile.indexOf("/", tmpIndex)+1);
			String mainCat = tempString.substring(0, tempString.indexOf("/"));
			tempString = tempString .substring(tempString.indexOf("/")+1);
			String singerOrFilm = tempString.substring(0, tempString.indexOf("/"));

			ps = conn.prepareStatement(insertContentSql);
			ps.setInt(1, nextCntId);
			ps.setString(2, contentName);
			ps.setInt(3, Integer.parseInt(categoryId));
			ps.setString(4, categoryName);
			ps.setString(5, originalFile);
			ps.setInt(6, Integer.parseInt(price));
			ps.setString(7, sampleImage);			
			ps.setString(8, ext);
			ps.setString(9, singerOrFilm);
			ps.setString(10, categoryName);
			ps.setString(11, mainCat + " - " + singerOrFilm);
			ps.setString(12, mainCat);
			ps.setString(13, point1);
			ps.setString(14, point2);
			ps.setString(15, bias);
			ps.setString(16, fillColor);
			
			if(1 == ps.executeUpdate()) {
				log.info("1 Content Record succcessfully inserted.");				
			}
		} catch(Exception e) {
			log.error("", e);
		} finally {
			if(ps != null)
				try {
					ps.close();
					ps = null;
				} catch (SQLException e) {
				}			
			dbProc.closeJNDIConnection(conn);
		}
	}
/**
	private void addWallPaper(String contentArr[], String reqContentStr, HttpServletResponse resp) {
		Connection conn = null;
		PreparedStatement ps = null;
		DBProc dbProc = DBProc.getInstance();
		try {
			conn = dbProc.getJNDIConnection();
			Vector<String> v = getTeamsName(conn);
			String team = v.elementAt(0);
			if(!matchName.equals(team))
				counter = 0;
			matchName = team;
			String filmOrSinger = v.elementAt(1);
			String sql = "select max(contentid) as cntid from content";
			ps = conn.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			int maxCntId = 0;
			if(rs.next()) {
				maxCntId = rs.getInt(1)+1;
			}
			sql = "INSERT INTO content (ContentID, ContentName, CategoryID, CategoryName, OriginalFile, Price, Status, ProviderID, " +
					"ContentImage, Format, Width, Height, AspectRatio, SingerOrFilm, ServiceURL, Parameters, Jspf, ContentSequence, " +
					"OrderSequence, InsertionTime, CategoryType, Description, SampleFile, ProviderContentID, Html, MainCat, Tags, " +
					"PriorityMultiplier, IsAuthorized, UpdatedBy, UpdatedAt, Point1, Point2, Bias, FillColor, DownloadTimes) " +
					"VALUES (?, ?, ?, ?, ?, ?, 1, 1, ?, ?, NULL, NULL, 1, ?, NULL, NULL, " +
					"NULL, 1, 2, now(), ?, 'Cricket T20', NULL, NULL, NULL, 'Cricket', '', NULL, 1, NULL, now(), NULL, NULL, NULL, " +
					"NULL, 0);";
			
			int categoryId = 3;
			String categoryName = "VIDEOS";
			int price = 25;
			String contentName = contentArr[0]; 
			String ext = contentArr[1];
			String categoryType = categoryName;
			String originalFileName = "cricketicc/"+reqContentStr;
			if("3gp".equals(ext)) {
				categoryId = 3;
				categoryName = "VIDEOS";
				price = 25;
				categoryType = categoryName;
			}			
			ps = conn.prepareStatement(sql);
			ps.setInt(1, maxCntId);
			ps.setString(2, contentName);
			ps.setInt(3, categoryId);
			ps.setString(4, categoryName);
			ps.setString(5, originalFileName);
			ps.setInt(6, price);
			ps.setString(7, "videos/cricketicc/"+team+(++counter)+".jpg");			
			ps.setString(8, ext);
			ps.setString(9, filmOrSinger);
			ps.setString(10, categoryType);
			if(1 == ps.executeUpdate()) {
				log.info("1 Content Record succcessfully inserted.");				
				//intimate wap push server that new content is there				
				String wapPushUrl = resp.encodeURL("http://70.33.254.33/download.jsp?cid="+maxCntId);
				log.info("Calling operators with parameters, cntId:"+maxCntId+", category:"+team+", pushURL:"+wapPushUrl);
				//call robincorp				
//				WapPortalBean wpb = new WapPortalBean();				
//				String urlResponse = wpb.getURLResponse("http://services.robincorp.net/CricketMessages/wappushsender.jsp?cid="+maxCntId+"&category="+team+"&url="+wapPushUrl);
//				log.info("** Zain urlResponse: "+urlResponse);
			}
		} catch(Exception e) {
			log.error("", e);
		} finally {
			if(ps != null)
				try {
					ps.close();
					ps = null;
				} catch (SQLException e) {
				}			
			dbProc.closeJNDIConnection(conn);
			if(counter >= 24)
				counter = 0;
		}
	}
**/
	private String getContentType(String contentId) {
		String cateType = null;
		Connection conn = null;
		PreparedStatement ps = null;
		DBProc dbProc = DBProc.getInstance();
		try {
			conn = dbProc.getJNDIConnection();
			String sql = "SELECT CategoryName FROM content WHERE ContentId = ? limit 1;";			
			ps = conn.prepareStatement(sql);
			ps.setString(1, contentId.trim());
			ResultSet rs = ps.executeQuery();
			if(rs.next())
				cateType = rs.getString(1);
			rs.close();
		} catch(Exception e) {
			log.error("Error inserting records for wap push download: ", e);
		} finally {
			if(ps != null)
				try {
					ps.close();
					ps = null;
				} catch (SQLException e) {
				}
			dbProc.closeJNDIConnection(conn);
		}
		return cateType;
	}
	
	private void printTextResponse(HttpServletResponse resp, String text) {
		try {			
			PrintWriter out = resp.getWriter();
			out.print(text);
			out.close();
		} catch (IOException e) {
			log.error("Error printing response: "+text, e);
		}		
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		processRequest(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		processRequest(req, resp);
	}
}
